package com.woniu.idearbac.Controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.woniu.idearbac.Service.PermissionService;
import com.woniu.idearbac.Service.UserService;


import com.woniu.idearbac.dto.UserDto;
import com.woniu.idearbac.entity.SysUser;
import com.woniu.idearbac.util.ObjectExcelRead;
import com.woniu.idearbac.util.ObjectExcelView;
import com.woniu.idearbac.util.PageData;
import com.woniu.idearbac.util.Result;
import com.woniu.idearbac.vo.PermissionVo;
import com.woniu.idearbac.vo.UserVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author King
 * @date 2022/11/24
 * @project boot_rbac
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private UserService UserService;
    @Resource
    private PermissionService permissionService;

    /**
     * 从EXCEL导入到数据库
     */
    @RequestMapping(value = "/importExcel")
    public Result importExcel(MultipartFile file, HttpServletRequest request) throws Exception {

        if (null != file && !file.isEmpty()) {
            //执行读EXCEL操作,读出的数据导入List 2:从第2行开始；0:从第A列开始；0:第0个sheet
            List<PageData> listPd = (List) ObjectExcelRead.readExcel(file.getInputStream(), 1, 0, 0);
            for (PageData pageData : listPd) {
                SysUser user = new SysUser();
                user.setRealName(pageData.getString("var0"));
                user.setTel(pageData.getString("var1"));

                user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(pageData.getString("var2")));
                String strDeptId = pageData.getString("var3");
                int deptId = 0;
                if (strDeptId.indexOf(".") != -1) {
                    deptId = Integer.parseInt(strDeptId.substring(0, strDeptId.indexOf(".")));
                } else {
                    deptId = Integer.parseInt(strDeptId);
                }
                user.setDeptId(deptId);

                UserService.insertSelective(user);
            }

        }
        return Result.ok("导入成功");
    }

    @RequestMapping(value = "/exportExcel")
    public ModelAndView exportExcel(@RequestBody UserDto user) {
        ModelAndView mv = new ModelAndView();
        try {
            Map<String, Object> dataMap = new HashMap<>();
            //构造列名称
            List<String> titles = new ArrayList<>();
            titles.add("用户编号"); // 1
            titles.add("姓名"); // 2
            titles.add("电话"); // 3
            titles.add("部门"); // 4
            dataMap.put("titles", titles);
            //得到被导出的数据
            List<UserVo> varOList = UserService.selAll(user);
            List<PageData> varList = new ArrayList<>();
            for (UserVo userVO : varOList) {
                PageData vpd = new PageData();
                vpd.put("var1", userVO.getId());
                vpd.put("var2", userVO.getRealName());
                vpd.put("var3", userVO.getTel());
                vpd.put("var4", userVO.getDeptName());
                varList.add(vpd);
            }
            dataMap.put("varList", varList);
            ObjectExcelView erv = new ObjectExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }


    @PostMapping("login")
    public Result login(@RequestBody UserDto UserDto) {
        SysUser sysUser = UserService.loginDo(UserDto);
        if (sysUser != null) {
            List<PermissionVo> vos = permissionService.selMenu(UserDto.getTel(), 0);
            return Result.ok().data("menuList", vos);
        } else {
            return Result.error();
        }
    }

    @PostMapping("selAll")
    public Result selAll(@RequestBody UserDto UserDto) {
        PageHelper.startPage(UserDto.getCurrentPage(), UserDto.getPageSize(), true);
        PageHelper.orderBy("id desc");
        List<UserVo> userVos = UserService.selAll(UserDto);
        PageInfo<UserVo> pageInfo = new PageInfo<>(userVos);
        return Result.ok().data("userList", userVos).data("total", pageInfo.getTotal());
    }

    @PostMapping("")
    public Result add(@RequestBody SysUser SysUser) {
        int i = UserService.insertSelective(SysUser);
        if (i > 0) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    @GetMapping("{id}")
    public Result selOne(@PathVariable Long id) {
        SysUser sysUser = UserService.selectByPrimaryKey(id);
        return Result.ok().data("list", sysUser);
    }

    @PutMapping("")
    public Result update(@RequestBody SysUser SysUser) {
        int i = UserService.updateByPrimaryKeySelective(SysUser);
        if (i > 0) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAuthority(\"user:delete\")")
    public Result del(@PathVariable Long id) {
        int i = UserService.deleteByPrimaryKey(id);
        if (i > 0) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }
}
